package com.chisheng.caa.pojo.response;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * 响应状态码
 */
public enum ResponseCode {

    SUCCESS(20000, "处理成功"),
    FAILURE(40000, "处理失败"),
    ILLEGAL_ARGUMENT_FAILURE(40001, "非法参数失败"),
    ERROR(50000, "服务错误");

    /**
     * 状态码
     */
    private final int code;

    /**
     * 原因
     */
    private final String reason;

    ResponseCode(int code, String reason) {
        this.code = code;
        this.reason = reason;
    }

    @JsonValue
    public int getCode() {
        return code;
    }

    public String getReason() {
        return reason;
    }

    /**
     * 返回状态值。若为成功状态码返回 true，否则 false。
     *
     * @return 状态值
     */
    public boolean getStatus() {
        return code % 10000 == 2;
    }

    @JsonCreator
    public static ResponseCode valueOf(int code) {
        for (ResponseCode status : ResponseCode.values()) {
            if (status.code == code) {
                return status;
            }
        }

        throw new IllegalArgumentException(String.format("无效状态码 '%s' 值", code));
    }

}
